<template>
  <div>
    <el-dialog v-if="!isMobile" title="支付" :visible.sync="dialogVisible" width="30%">
      <div style="text-align: center">
        <div class="text-danger" style="font-size: 12px;margin-bottom: 10px">
          * 使用微信扫码支付，支付中不要关闭弹窗，支付完成之后自动提交
        </div>
        <div>{{ payParams.goodsDesc }}</div>
        <h2 class="text-danger">
          ￥{{ payParams.totalPrice }}
        </h2>
        <vue-qr v-if="payParams.codeUrl" :text="payParams.codeUrl" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <van-popup v-else v-model="dialogVisible" round position="bottom" :style="{ height: '30%' }">
      <div style="margin: 20px">
        <div class="text-danger" style="font-size: 12px;margin-bottom: 10px">
          * 点击后跳转至微信支付页面，支付完成后回到页面并自动提交
        </div>
        <h2 class="text-center">
          {{ payParams.goodsDesc }}
        </h2>
      </div>
      <van-submit-bar :price="payParams.totalPrice*100" button-text="去支付" @submit="jumpMWebPay" />
    </van-popup>
  </div>
</template>

<script>
import {isMobile} from "../../../formgen/src/utils"
import {request} from "../../../formgen/src/api/request"
import {isWxEnv} from './wx'
import {Dialog, Popup, SubmitBar} from 'vant'
import 'vant/lib/popup/style'
import 'vant/lib/submit-bar/style'
import 'vant/lib/dialog/style'
import {getFormData, removeFormData, saveFormData} from "../../../formgen/src/utils/db"
import {getQueryString} from "../../../utils"


export default {
  name: "GoodsPay",
  components: {
    'vue-qr': (resolve) => require(['vue-qr/src/packages/vue-qr'], resolve),
    [Popup.name]: Popup,
    [SubmitBar.name]: SubmitBar
  },
  data() {
    return {
      dialogVisible: false,
      randKey: '',
      payParams: {
        codeUrl: '',
        goodsDesc: '',
        totalPrice: '',
        mwebUrl: ''
      },
      isMobile: isMobile(),
      //交易id
      transactionId: '',
      payStatusTimer: null,
      // 临时存储
      tempFormModel: {},
      formKey: ''
    }
  },
  created() {
    let source = this.$route.query.source
    this.randKey = this.$route.query.randKey
    this.formKey = this.$route.params.key
    this.tempFormModel = {formModel: getFormData(this.formKey)}
    // 微信内jsapi支付需要先获取openid
    if (source === 'pay' && this.isMobile && getFormData(this.formKey)) {
      Dialog.confirm({
        title: '提示',
        confirmButtonText: '完成',
        cancelButtonText: '放弃',
        message: '您的微信支付是否已经完成？'
      }).then(() => {
        this.queryPayStatus()
      })
        .catch(() => {
          // on cancel
        })
    }
  },
  destroyed() {
    clearInterval(this.payStatusTimer)
  },
  methods: {
    /**
     * 是否使用jsapi支付
     */
    wxJsApiPay() {
      if (!isWxEnv()) {
        return
      }
      // 判断是否在微信环境内
      let fields = this.$parent.$refs.bizProjectForm.formConf.fields
      if (fields) {
        let haveGoods = fields.filter((item) => item.vModel.indexOf("goods_select") > -1).length > 0
        if (haveGoods && !getQueryString('code')) {
          location.href = this.$parent.wxAuthorizationUrl
        }
      }
    },
    openPay(data, formKey) {
      if (this.transactionId) {
        this.transactionId = ''
        return false
      }
      const {
        formModel
      } = data
      this.tempFormModel = data
      let payComs = []
      Object.keys(formModel).forEach((key) => {
        if (key.indexOf("goods_select") > -1) {
          if (Object.keys(formModel[key]).length !== 0) {
            payComs.push({key: key, value: formModel[key]})
          }
        }
      })
      //生成随机Id
      // 随机5位数字
      this.randKey = this.getNowFormatDate() + (Math.floor(Math.random() * 90000) + 10000)
      let openId = this.$parent.wxUserInfo ? this.$parent.wxUserInfo.openid : ''
      if (payComs.length !== 0) {
        request
          .post("/form/ext/createGoodsPay", {
            formKey: formKey,
            randKey: this.randKey,
            isMobile: isMobile(),
            openId: openId,
            goodsList: payComs
          })
          .then((res) => {
            this.payParams = res.data
            if (!this.isMobile) {
              this.queryPayStatus()
            }
          }).catch((err) => {
          this.dialogVisible = false
        })
        this.dialogVisible = true
        return true
      }
      return false
    },
    /**
     * 查询支付状态
     */
    queryPayStatus() {
      this.payStatusTimer = setInterval(() => {
        request.get("/form/ext/queryPayStatus", {
          params: {
            randKey: this.randKey
          }
        }).then((res) => {
          if (res.data) {
            this.transactionId = res.data
            this.$message({
              message: '支付成功',
              type: 'success'
            })
            this.dialogVisible = false
            this.tempFormModel.formModel.payRandKey = this.randKey
            removeFormData(this.formKey)
            clearInterval(this.payStatusTimer)
            this.$emit('paySuccess', this.tempFormModel)
          }
        })
      }, 3000)
    },
    jumpMWebPay() {
      // 微信里面使用jsapi支付
      if (isWxEnv()) {
        this.handleJsApiPay()
        return
      }
      if (!this.payParams.mwebUrl) {
        return
      }
      // 其他浏览器使用H5支付
      saveFormData(this.tempFormModel.formModel, this.formKey)
      // 获取当前域名 去除?后面的参数
      let url = window.location.href.split('?')[0]
      let redirectUrl = `${url}?source=pay&randKey=${this.randKey}`
      window.location.href = this.payParams.mwebUrl + '&redirect_url=' + encodeURIComponent(redirectUrl)
    },
    handleJsApiPay() {
      let that = this
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            that.onBridgeReady,
            false
          )
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", that.onBridgeReady)
          document.attachEvent("onWeixinJSBridgeReady", that.onBridgeReady)
        }
      } else {
        this.onBridgeReady()
      }
    },
    onBridgeReady() {
      let that = this
      // 调用获取支付签名接口
      let {appId, timeStamp, nonceStr, packageValue, signType, paySign} = this.payParams
      // eslint-disable-next-line no-undef
      WeixinJSBridge.invoke("getBrandWCPayRequest", {
          appId, // 微信的appid
          timeStamp, //时间戳
          nonceStr, //随机串
          package: packageValue,  // 订单号
          signType, //微信签名方式：
          paySign //微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            that.queryPayStatus()
          }
        }
      )
    },
    /**
     * 获取当前时间 YYYYMMDDHHmmss
     */
    getNowFormatDate() {
      let date = new Date()
      let month = date.getMonth() + 1
      let strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = "0" + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate
      }
      let currentdate =
        date.getFullYear() +
        month +
        strDate +
        date.getHours() +
        date.getMinutes() +
        date.getSeconds()
      return currentdate
    }
  }
}
</script>

<style scoped></style>
